/**----------------------------------------------------------*/
/** JS:  cmi_properties_list.js（商品管理--商品属性）           */
/**----------------------------------------------------------*/

var tipc = 'GOODS_CATEGROY_PROPERTIES';
var win = null;

var add = function() {
	try {
		var div = getEditDiv();
		win = MyUtils._getToolbarWin("dataPanel", "dateEdit", div, submitAdd, panel +"--新增","保存提交");
		win.window({
			width:790,
			height:370,
			modal: true
		});
		repainProperties(null);
	} catch (e) {
		showJsException(e);
	}
};

var modify = function() {
	try{
		var record = datagridOneRow('dataPanel');
		if(record == null) {
			return;
		}
		var div = getEditDiv();
		win = MyUtils._getToolbarWin("dataPanel", "dateEdit", div, submitModify, panel +"--修改","保存提交");
		win.window({
			width:790,
			height:370,
			modal: true
		});
		repainProperties(record);
	} catch(e) {
		showJsException(e);
	}
};

var remove = function() {
	try{
		var rows = $('#dataPanel').datagrid("getSelections");
		if(rows.length == 0) {
			MyUtils.waring(_empty_select);
			return;
		}
		var ids = new Array();
		var names = new Array();
		for(var i = 0; i < rows.length; i++) {
			ids.push(rows[i].uuid);
			names.push(rows[i].categroy);
		}
		var data = { data:"["+MyUtils.createQueryConditionBean("uuid","customer","uuid IN (" + ids.toString() + ")","0",null) +"]"
			    ,st:tipc
			    ,msg:names.toString()
		};
		$.messager.confirm(_msg_sys,MyUtils.valueAlign(_remove_confirm,"left"), function(r) {
			if (r) {
				MyUtils.openMask(_msg_process,$('#t2'));
				MyUtils.sendPost("impl_remove/backRemove.adm",data,function(rets){
					try{
						MyUtils.hiddenMask($('#t2'));
						var res = MyUtils.toJsonObject(rets);
						if(res.error == '0') {
							MyUtils.info(res.msg);
							$('#dataPanel').datagrid("clearSelections");
							$('#dataPanel').datagrid("reload");
						} else {
							MyUtils.error(res.msg);
						}
					} catch (e) {
						showJsException(e);
					}
				});
			}
		});
		
	} catch(e) {
		showJsException(e);
	}
};


var dbclick = function(index,row){
	$('#dataPanel').datagrid("clearSelections");
	$('#dataPanel').datagrid("selectRow",index);
	modify();
};

var initPanel = function() {
	var toolbars = [ {"handler":"add","iconCls":"icon-add","id":"tb_add","text":"添加"}
					,{"handler":"modify","iconCls":"icon-edit","id":"tb_modify","text":"修改"}
					,{"handler":"remove","iconCls":"icon-remove","id":"tb_remove","text":"删除"}
				  ];
	var columns = [  {field : 'uuid',title : '编号',width : 100,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"left");},sortable:true}
					,{field : 'proName',title : '属性名称',width : 200,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"left");},sortable:true}
					,{field : 'categroyIdName',title : '商品类型',width : 150,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"left");},sortable:true}
					,{field : 'inputs',title : '属性值的录入方式',width : 150,align : 'center',formatter:function(value){
						for(var i = 0; i < dm5.length;i++){
							if(dm5[i].dmcode == value) {
								return MyUtils.valueAlign(dm5[i].dmname,"left");
							}
						}
						return MyUtils.valueAlign(value,"left");
					  },sortable:true}
					,{field : 'valueList',title : '可选值列表',width : 150,align : 'center',formatter:function(value){
						value = value.replace(/\n/g,",");
						return MyUtils.valueAlign(value,"left");
					}}
					,{field : 'psort',title : '排序',width : 90,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"right");}}
				];
	var pam = {qr:"[]",st:tipc,sco:'',dc:Dmlx.sort.desc};
	if(passCategroy !=  '0') {
		pam = {qr:"["+MyUtils.createQueryConditionBean("categroyId","=","?", passCategroy,null) +"]",st:tipc,sco:'',dc:Dmlx.sort.desc};
	} 
	MyUtils.createPaginPanelWithQueryparams('dataPanel',null,Dmlx._hFrozenColumns,columns,toolbars,dbclick, panel,null);
	$('#dataPanel').datagrid({
		url:"impl_search/commonsPaginSearch.ajax",
		queryParams:pam,
		pagination:true,
		fitColumns:true
	});
};

$(function(){
	try {
		initPanel();
		$('#cateSearch').combobox({
			 url:"impl_search/searchObjectList.ajax?st=GOODS_CATEGROY&qy=" 
			,valueField:"uuid" 
			,textField:"categroy"
		    ,onSelect:function(record) {
		    	var pam = {qr:"[]",st:tipc,sco:'',dc:Dmlx.sort.desc};
				if(record.uuid !=  '0') {
					pam = {qr:"["+MyUtils.createQueryConditionBean("categroyId","=","?", record.uuid,null) +"]",st:tipc,sco:'',dc:Dmlx.sort.desc};
				} 
				MyUtils._searchPanelData('dataPanel', 'impl_search/commonsPaginSearch.ajax', pam);
		    }
			,value:passCategroy
		});
		    
	} catch (e) {
		showJsException(e,"数据加载失败!");
	}	
});

var submitAdd = function(){
	try {
		var dt = editValidator();
		if(dt != null) {
			var data = {dt:dt,st:tipc};
			MyUtils.openMask(_msg_process,win);
			submitDate("impl_add/backAdd.adm",data);
		}
	} catch (e) {
		MyUtils.hiddenMask(win);
		showJsException(e,_msg_fail);
	}
};

var submitModify = function(){
	try {
		var dt = editValidator();
		if(dt != null) {
			var data = {dt:dt,st:tipc,qy:"[]"};
			$.messager.confirm(_msg_sys,MyUtils.valueAlign(_modify_confirm,"left"), function(r) {
				if(r) {
					MyUtils.openMask(_msg_process,win);
					submitDate("impl_modify/backModify.adm",data);
				}
			});
		}
	} catch (e) {
		MyUtils.hiddenMask(win);
		showJsException(e,_msg_fail);
	}
};

var editValidator = function(){
	var record = {
			 uuid:$('#uuid').val()
			,proName:$('#proName').val()
			,categroyId:$('#categroyId').combobox("getValue")
			,groups:$('#groups').val()
			,searchAble:$('input[name="dm3"]:checked').val()
			,relationAble:$('input[name="dm1"]:checked').val()
			,choseAble:$('input[name="dm4"]:checked').val()
			,inputs:$('input[name="dm5"]:checked').val()
			,valueList:$('#mtext').val()
			,psort:$('#psort').val()
		};
	
	if(record.inputs != 2) {
		record.valueList ='';
	}
	
//	if(record.valueList.length > 0) {
//		record.valueList = record.valueList.replace(/\n/g,",");
//	}
	
	//验属性名称
	if(MyUtils.isEmpty(record.proName)) {
		MyUtils.waring("属性名称名称不能为空");
		return null;
	}
	//验所属商品类型
	if(MyUtils.isEmpty(record.categroyId) || record.categroyId == 0) {
		MyUtils.waring("请选择所属商品类型");
		return null;
	}
	return MyUtils.toJsonStr(record);
};

var submitDate = function(url,data) {
	MyUtils.sendPost(url,data,function(msg){
		try{
			MyUtils.hiddenMask(win);
			var res = MyUtils.toJsonObject(msg);
			if(res.error == '0') {
				if(win)win.window('close');
				$('#dataPanel').datagrid("clearSelections");
				$('#dataPanel').datagrid("reload");
			} else {
				MyUtils.error(res.msg);
			}
		} catch (e) {
			MyUtils.hiddenMask(win);
			MyUtils.error(_msg_fail);
		}
	});
};

var getEditDiv = function() {
	var div='<table cellspacing="2" cellpadding="6" id="dateEdit">'
		+'<tbody>'
			+'<tr>'
				+'<th align="right" width=200>属性名称：</th>'
				+'<td align="left" width=500>'
					+'<input type="hidden" id="uuid" value="" >'
					+'<input type="text" id="proName" maxlength="120" id="" style="width: 288px;" value=""><label class="requre_field">*</label>'
				+'</td>'
			+'</tr>'
			+'<tr>'
			+'<th align="right" width=200>所属商品类型：</th>'
			+'<td align="left">'
				+'<select id="categroyId" style=";width: 150px;"></select><label class="requre_field">*</label>'
			+'</td>'
			+'</tr>'
			+'<tr id="group_1" style="display: none;">'
			+'<th align="right" width=200>属性分组：</th>'
			+'<td align="left">'
				+'<select id="groups" style="width: 150px;"></select></td>'
			+'</tr>'
			+'<tr id="sort_1" style="display: none;">'
			+'<th align="right" width=200>排序：</th>'
			+'<td align="left">'
				+'<input type="text" id="psort" maxlength="5" value="0" style="width: 80px;">'
			+'</td>'
			+'</tr>'
			+'<tr>'
			+'<th align="right" width=200 valign="top">能否进行检索：</th>'
			+'<td align="left">'
			+'<input type = "radio" name="dm3"  value="1"	>不需要检索</input>'
			+'<input type = "radio" name="dm3"  value="2"	>关键字检索</input>'
			+'<input type = "radio" name="dm3"  value="3"	>范围检索</input>'
			+'<div style="color:gray;">不需要该属性成为检索商品条件的情况请选择不需要检索，需要该属性进行关键字检索商品时选择关键字检索，如果该属性检索时希望是指定某个范围时，选择范围检索。</div>'			
			+'</td>'
			+'</tr>'
			+'<tr>'
			+'<th align="right" width=200>相同属性值的商品是否关联：</th>'
			+'<td align="left">'
			+'<input type = "radio" name="dm1"  value="0"	>否</input>'
			+'<input type = "radio" name="dm1"  value="1"	>是</input></td>'
			+'</tr>'
			+'<tr>'
			+'<th align="right" width=200 valign="top">属性是否可选：</th>'
			+'<td align="left" >'
			+'<input type = "radio" name="dm4"  value="1"   >唯一属性</input>'
			+'<input type = "radio" name="dm4"  value="2"	>单选属性</input>'
			+'<input type = "radio" name="dm4"  value="3"	>复选属性</input>'
			+'<div style="color:gray;">选择"单选/复选属性"时，可以对商品该属性设置多个值，同时还能对不同属性值指定不同的价格加价，用户购买商品时需要选定具体的属性值。选择"唯一属性"时，商品的该属性值只能设置一个值，用户只能查看该值。</div>'			
			+'</td>'
			+'</tr>'
			+'<tr>'
			+'<th align="right" width=200>该属性值的录入方式：</th>'
			+'<td align="left">'
			+'<input type = "radio" name="dm5"  value="1"	> 手工录入 </input>'
			+'<input type = "radio" name="dm5"  value="2"	> 从下面的列表中选择（一行代表一个可选值）</input>'
			+'<input type = "radio" name="dm5"  value="3"	>多行文本框 </input>'	
			+'</td>'
			+'</tr>'
			+'<tr>'
			+'<th align="right" width=200>可选值列表:</th>'
			+'<td align="left"><textarea rows="6" cols="31" id="mtext" name="mtext" style="width: 300px;" readonly="readonly"></textarea></td>'
			+'</tr>'
			+'</tbody>'
			+'</table>';
	return div;
};

var repainProperties =function(record){
	var searchDatas = $('#cateSearch').combobox("getData");
	var selectCategroy = $('#cateSearch').combobox("getValue");
	var copyArray = function(from) {
		var to = new Array();
		var rcd = null;
		for(var i = 0; i < from.length; i++) {
			if(from[i].uuid == 0) {
				rcd = {
					uuid:from[i].uuid
				   ,categroy:'请选择...'
				   ,groups:from[i].groups
				   ,fieldCt:0
				   ,intime:''
				   ,state:0
				   ,uptime:""
				};
			} else {
				rcd = from[i];
			}
			to.push(rcd);
		}
		return to;
	};
	
	var getSelectRecord = function(data,id) {
		for(var i=0; i < data.length;i++) {
			if(data[i].uuid == id) {
				return data[i];
			}
		}
		return null;
	};
	
	var showGroups = function(show,record) {
		if(show) {
			var div ='<option value="'+record.groups+'">'+record.groups+'</option>';
    		$('#group_1').show();
    		$('#groups').append(div);
		} else {
			$('#group_1').hide();
    		$('#groups').empty();
		}
	};
	var datas = copyArray(searchDatas);
	/*
	 * 设置参数
	 */
	selectCategroy = record ? record.categroyId : selectCategroy;
	$('#categroyId').combobox({
		 url:null
		,valueField:"uuid" 
		,textField:"categroy"
		,data:datas
	    ,onSelect:function(record) {
	    	showGroups((MyUtils.trim(record.groups).length > 0),record);
	    }
		,value:selectCategroy
	});
	
	var selectRcd = getSelectRecord(searchDatas,selectCategroy);
	showGroups((selectRcd != null && MyUtils.trim(selectRcd.groups).length > 0),selectRcd);
	
	$('input[name="dm3"][value='+(record ? record.searchAble : 1)+']').attr("checked",true);
	$('input[name="dm1"][value='+(record ? record.relationAble : 0)+']').attr("checked",true);
	$('input[name="dm4"][value='+(record ? record.choseAble : 1)+']').attr("checked",true);
	$('input[name="dm5"][value='+(record ? record.inputs : 1)+']').attr("checked",true);
	
	if(record && record.inputs == 2) {
		$('#mtext').attr("readonly",false);
//		$('#mtext').val(record.valueList.replace(/,/g,"\n"));
		$('#mtext').val(record.valueList);
	} else {
		$('#mtext').attr("readonly",true);
	}
	
	if(record) {
		$('#uuid').val(record.uuid);
		$('#proName').val(record.proName);
		$('#sort_1').show();
	} else {
		$('#sort_1').hide();
	}
	
	$('input[name="dm5"]').live("click",function(msg){
		if(this.value==2) {
			$('#mtext').attr("readonly",false);
		} else {
			$('#mtext').attr("readonly",true);
		}
	});
};

